#define BOOL unsigned char
#define TRUE 1
#define FALSE 0
#define ON 1
#define OFF 0
#define UP 1
#define DOWN 0
#define SLOW 1
#define FAST 0

#include "mb90560.h"
#include "main.h"

#include "CountdownTimer.h"
#include "HardwareOut.h"
#include "HardwareIn.h"
#include "ElevatorLogic.h"
#include "AbstractApplication.h"
#include "Serial.h"
#include "SerialRead.h"
#include "SerialWrite.h"

#include "CountdownTimer.c"
#include "HardwareOut.c"
#include "HardwareIn.c"
#include "ElevatorLogic.c"
#include "AbstractApplication.c"
#include "Serial.c"
#include "SerialRead.c"
#include "SerialWrite.c"


/*
global functions for use in the other components
*/
void time (int t)
{
	int p;
	while (t > 0)
	{
		for (p=0; p<888; p++) /* 888 ~~ 1ms */
			continue;
		t--;
	}
}
void beep (int times)
{
	int i;
	for (i=0; i<times; i++)
	{
		PDR1_P11 = ON;
		time(50);
		PDR1_P11 = OFF;
		time(50);
	}
	time(150);
}

void enableInterrupts ()
{
	// initialize cpu interrupt settings
	__set_il(7); // set the interrupt level mask to 7 (lowest)
    __EI(); // set the interrupt enable bit on the cpu
}

void main (void)
{
	int i;
	// startup sequence
	HardwareIn_Initialize();
	CountdownTimer_Initialize();
	Serial_Initialize();
	HardwareOut_Initialize();
	ElevatorLogic_Initialize();
	AbstractApplication_Initialize();
	beep(3);
	
	// timing test
	if (FALSE)
	{
		PDR1_P11 = ON;
		time(50);
		PDR1_P11 = OFF;
		time(950);
		time(5000);
		time(6000);
		time(6000);
		time(6000);
		time(6000);
		PDR1_P11 = ON;
		time(50);
		PDR1_P11 = OFF;
	}
	
	// HardwareIn tests
	if (FALSE)
	{
		HardwareIn_MoveDown(SLOW);
		time(1000);
		HardwareIn_MoveDown(FAST);
		time(1000);
		HardwareIn_MoveDown(SLOW);
		time(500);
		HardwareIn_StopMoving();
		time(1500);
		HardwareIn_MoveUp(FAST);
		time(500);
		HardwareIn_StopMoving();
		for (i=0; i<4; i++)
		{
			HardwareIn_SetLed(i);
			HardwareIn_SetNumberDisplay(i);
			time(500);
		}
		time(1000);
		HardwareIn_UnsetLed(0);
		HardwareIn_UnsetLed(1);
		HardwareIn_UnsetLed(2);
		HardwareIn_UnsetLed(3);
		HardwareIn_SetBuzzer();
		time(1000);
		HardwareIn_UnsetBuzzer();
	}
	
	enableInterrupts();
	
	// main program
	while (TRUE)
	{
		HardwareOut_CheckOutput();
		SerialRead_CheckInput();
		ElevatorLogic_Operate();
	}
}
